import 'package:casdon/common/service/tuya_service.dart';
import 'package:casdon/core/logger/log.dart';
import 'package:casdon/core/utils/toast_utils.dart';
import 'package:casdon/modules/recipe/application/notification/recipe_products_notifier.dart';
import 'package:casdon/modules/recipe/data/api/miffy_recipe_info_api.dart';
import 'package:casdon/modules/recipe/data/model/miffy_recipe_info_model.dart';
import 'package:casdon/modules/recipe/domain/states/recipe_dispatch_state.dart';
import 'package:casdon/modules/recipe/domain/usecase/miffy_recipe_info_usecase.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:tuya_home_sdk_flutter/tuya_home_sdk_flutter.dart';

// miffy 下发菜谱, 仅在智能页面会用到，其他地方都是ciot云菜谱
class MiffyRecipeDispatchNotifier
    extends AutoDisposeAsyncNotifier<RecipeDispatchState> {
  ResponseMiffyRecipeInfoApi? recipeInfoApi;
  @override
  Future<RecipeDispatchState> build() async {
    return RecipeDispatchState.initial();
  }

  Future<void> fetchData({
    required String recipeId,
    required String? devId,
  }) async {
    try {
      state = AsyncLoading();

      if (devId == null) {
        ToastUtil.show("无可用设备");
        return;
      }
      final devList = await TuyaService().homeDeviceList();
      final ThingSmartDeviceModel targetDevice = devList.firstWhere(
        (e) => e.devId == devId,
      );

      // 获取miffy菜谱详细信息
      final recipeInfoApi = await ref
          .read(miffyRecipeInfoUsecaseProvider)
          .execute(recipeId: recipeId);
      MiffyRecipeProtocolModel? recipeInfoModel =
          MiffyRecipeProtocolModel.fromApi(
            recipeInfoApi,
            devModel: targetDevice,
          );
      if (recipeInfoModel == null) {
        return;
      }
      RecipeDispatchState newState = RecipeDispatchState(
        ecoModel: recipeInfoModel,
        devList: [targetDevice],
        devIndex: 0,
        recipeId: recipeId,
      );
      state = AsyncData(newState);
    } catch (e, st) {
      state = AsyncError(e, st);
      ToastUtil.show("获取数据失败");
      Log.e("RecipeDispatchNotifier fetchData failed", e.toString(), st);
    }
  }

  // 下发菜谱
  Future<bool> dispatch() async {
    if (state.value == null) return false;
    if (!_checkCanDispatch()) return false;

    Map<String, dynamic>? dps = state.value!.ecoModel?.dps;
    if (dps == null) return false;

    final devModel = state.value!.devList?[state.value!.devIndex ?? 0];
    if (devModel == null) return false;
    Log.i("miffy菜谱下发 = ${devModel.devId}: $dps");
    try {
      final ret = await TuyaService().publishDps(
        deviceId: devModel.devId!,
        dps: dps,
      );

      if (ret == false) {
        ToastUtil.show("菜谱下发失败");
        Log.i("miffy菜谱下发失败");
        return false;
      } else {
        ToastUtil.show("菜谱下发成功");
        Log.i("miffy菜谱下发成功");
        return true;
      }
    } catch (e, st) {
      ToastUtil.show("菜谱下发失败");
      Log.e("miffy菜谱下发失败: ${devModel.devId}", e.toString(), st);
      return false;
    }
  }

  void updateSelectedIndex(int value) {
    if (state.value == null) {
      return;
    }
    if (state.value!.devList == null || state.value!.devList!.isEmpty) {
      return;
    }
    if (value >= state.value!.devList!.length) {
      return;
    }
    RecipeDispatchState stateData = state.value!;
    stateData = stateData.copyWith(devIndex: value);
    state = AsyncData(stateData);
  }

  /** 
 *  cook_status
 * reservation预约中 
 * cooking烹饪中 
 * cancel烹饪取消 
 * wait烹饪等待 
 * done烹饪完成 
 * pause烹饪暂停 
 * preheating预热，
 * preheat_warming预热完成保温中（APP上取消时，APP下发cancel或wait）
 * standby待机中
 */
  bool _checkCanDispatch() {
    if (state.value == null) {
      return false;
    }
    if (state.value!.devList == null || state.value!.devList!.isEmpty) {
      return false;
    }
    final ThingSmartDeviceModel model =
        state.value!.devList![state.value!.devIndex ?? 0];

    if (!model.isOnline) {
      ToastUtil.show("产品已离线，启动失败！");
      return false;
    }
    int statusDpCode = -1;
    for (ThingSmartSchemaModel schema in model.schemaArr ?? []) {
      if (schema.code == "cook_status") {
        statusDpCode = schema.id;
      }
    }
    if (statusDpCode == -1) {
      return false;
    }
    Map? dps = model.dps;
    if (dps == null) return false;
    if (dps.containsKey(statusDpCode.toString()) == false) return false;
    String dpValue = dps[statusDpCode.toString()];
    if (dpValue == "wait" ||
        dpValue == "done" ||
        dpValue == "cancel" ||
        dpValue == "standby") {
      return true;
    }
    ToastUtil.show("请先取消当前工作！");
    return false;
  }

  int getDpidWithDpCode({required String dpCode}) {
    final ThingSmartDeviceModel model =
        state.value!.devList![state.value!.devIndex ?? 0];
    for (var schemaModel in model.schemaArr!) {
      if (dpCode == schemaModel.code) {
        return schemaModel.id;
      }
    }
    return 0;
  }

  String? getDpTypeWithDpCode({required String dpCode}) {
    final ThingSmartDeviceModel model =
        state.value!.devList![state.value!.devIndex ?? 0];
    if (model.schemaArr == null) return null;
    for (var schemaModel in model.schemaArr!) {
      if (dpCode == schemaModel.code) {
        return propertyTypeValues.reverse[schemaModel.property!.type];
      }
    }
    return null;
  }
}

final miffyRecipeDispatchNotifierProvider =
    AsyncNotifierProvider.autoDispose<
      MiffyRecipeDispatchNotifier,
      RecipeDispatchState
    >(MiffyRecipeDispatchNotifier.new);
